﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace MASAS.Feature.Addons.WebParts.NotificationDashboard
{

    /// <summary>
    /// Class NotificationDashboardUserControl.
    /// </summary>
    public partial class NotificationDashboardUserControl : UserControl
    {

        // Private members...
        private DashboardData   _dashboardData  = new DashboardData();
        private int             _timerValue     = ( 30 * 1000 );        // Update the data every 30 seconds.
        private bool            _showIgnored;
        private string          _listName;
        private string          _expirationFieldName;
        private string          _trackingFieldName;

        /// <summary>
        /// Updates the attributes.
        /// </summary>
        public void UpdateAttributes()
        {
            _showIgnored = Convert.ToBoolean( this.Attributes["ShowIgnored"] );
            _listName = Convert.ToString( this.Attributes["ListName"] );
            _expirationFieldName = Convert.ToString( this.Attributes["ExpirationFieldName"] );
            _trackingFieldName = Convert.ToString( this.Attributes["TrackingFieldName"] );

            grpIgnore.Visible = _showIgnored;

            RefreshData();
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load( object sender, EventArgs e )
        {
            refreshTimer.Interval = _timerValue;

            UpdateAttributes();
        }

        /// <summary>
        /// Handles the Tick event of the refreshTimer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void refreshTimer_Tick( object sender, EventArgs e )
        {
            RefreshData();
        }

        /// <summary>
        /// Refreshes the data.
        /// </summary>
        private void RefreshData()
        {
            SPWeb web = SPControl.GetContextWeb( Context );
            
            SPList list = web.Lists.TryGetList( _listName );

            if( list != null && list.Fields.ContainsField( _expirationFieldName ) && list.Fields.ContainsField( _trackingFieldName ) )
            {
                string camlQueryXml;

                if( _showIgnored )
                {
                    camlQueryXml = @"<View><Query>
                                    <Where>
                                        <Geq>
                                            <FieldRef Name='" + _expirationFieldName + @"' />
                                            <Value Type='DateTime'><Today/></Value>
                                        </Geq>
                                    </Where>
                                </Query></View>";
                }
                else
                {
                    camlQueryXml = @"<View><Query>
                                    <Where>
                                        <And>
                                            <Geq>
                                                <FieldRef Name='" + _expirationFieldName + @"' />
                                                <Value Type='DateTime'><Today/></Value>
                                            </Geq>
                                            <Neq>
                                                <FieldRef Name='" + _trackingFieldName + @"' />
                                                <Value Type='Choice'>Ignore</Value>
                                            </Neq>
                                        </And>
                                    </Where>
                                </Query></View>";
                }

                SPQuery query = new SPQuery();
                query.ViewXml = camlQueryXml;

                SPListItemCollection items = list.GetItems( query );

                BindData( items );
            }
        }

        /// <summary>
        /// Binds the data from the SP list to the Data Grid.
        /// </summary>
        /// <param name="items">The items.</param>
        private void BindData( SPListItemCollection items )
        {
            List<HubItem> hubItems = new List<HubItem>();

            if( items.Count > 0 )
            {
                foreach( SPListItem listItem in items )
                {
                    HubItem hubItem = new HubItem();

                    hubItem.Identifier = Convert.ToInt32( listItem["ID"] );
                    hubItem.TrackingState = listItem[_trackingFieldName].ToString();

                    hubItems.Add( hubItem );
                }
            }

            _dashboardData.ClearTotals();
            _dashboardData.TotalNumberOfItems = items.Count;

            var trackingStateCounts = from p in hubItems
                                      group p by p.TrackingState into g
                                      select new TrackingStateCount { TrackingState = g.Key, TrackingCount = g.Count() };

            foreach( TrackingStateCount tsCount in trackingStateCounts )
            {
                if( tsCount.TrackingState == "Action" )
                {
                    _dashboardData.NumberOfActionItems = tsCount.TrackingCount;
                }
                else if( tsCount.TrackingState == "Monitor" )
                {
                    _dashboardData.NumberOfMonitorItems = tsCount.TrackingCount;
                }
                else if( tsCount.TrackingState == "Ignore" )
                {
                    _dashboardData.NumberOfIgnoredItems = tsCount.TrackingCount;
                }
                else if( tsCount.TrackingState == "None" )
                {
                    _dashboardData.NumberOfNoneItems = tsCount.TrackingCount;
                }
            }

            lblTotalValue.InnerText = _dashboardData.TotalNumberOfItems.ToString();
            lblActionValue.InnerText = _dashboardData.NumberOfActionItems.ToString();
            lblMonitorValue.InnerText = _dashboardData.NumberOfMonitorItems.ToString();
            lblIgnoreValue.InnerText = _dashboardData.NumberOfIgnoredItems.ToString();
            lblNoneValue.InnerText = _dashboardData.NumberOfNoneItems.ToString();

            if( _dashboardData.NumberOfActionItems > 0 )
            {
                grpAction.Attributes["class"] = "masas-ndwp-trackingNV-red";
            }
            else
            {
                grpAction.Attributes["class"] = "masas-ndwp-trackingNV";
            }

            if( _dashboardData.NumberOfMonitorItems > 0 )
            {
                grpMonitor.Attributes["class"] = "masas-ndwp-trackingNV-yellow";
            }
            else
            {
                grpMonitor.Attributes["class"] = "masas-ndwp-trackingNV";
            }
        }

    }

}
